package com.dream.xcarrecorder;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.dream.xcarrecorder.rec.CameraHelper;
import com.dream.xcarrecorder.rec.RecHelper;

/**
 * 将录制及相关的业务都和UI解耦，方便后续扩展，如果要看直接的调用，可以看MainActivity类
 */
public class MainActivity2 extends Activity implements View.OnClickListener{
    private Context mContext;
    private ImageView mPicIV;
    private Button mBtnRec,mBtnTakPic,mBtnPreview;
    private LinearLayout mPreviewLayout = null;
    private final RecHelper mRecHelper = RecHelper.getInstance();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        mContext = this;


        initView();
        checkPermission();
//        finish();
    }

    private void checkPermission(){
        boolean isGrantedCamera = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED;
        boolean isGrantedAudioRecord =  ActivityCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED;

        if (isGrantedCamera||isGrantedAudioRecord){
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.RECORD_AUDIO
                    },0);
        }else{
            RecService.start(mContext);
        }
    }

    private void initView() {
        mPreviewLayout =
                findViewById(R.id.main_btn_rec_preview_layout);
        mPicIV = findViewById(R.id.main_img_pic);
        mPicIV.setOnClickListener(this);
        mBtnRec = findViewById(R.id.main_btn_rec);
        mBtnRec.setOnClickListener(this);
        mBtnRec.setEnabled(true);
        mBtnTakPic = findViewById(R.id.main_btn_takepic);
        mBtnTakPic.setOnClickListener(this);
        mBtnPreview = findViewById(R.id.main_btn_preview);
        mBtnPreview.setOnClickListener(this);
        findViewById(R.id.main_btn_rec_list).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.main_btn_takepic){
            mRecHelper.takePhoto(0, new CameraHelper.ITakePhotoListener() {
                @Override
                public void onTakePhoto(String channel, Bitmap bitmap) {
                    runOnUiThread(() -> {
                        mPicIV.setImageBitmap(bitmap);
                        mPicIV.setVisibility(View.VISIBLE);
                    });
                }
            });
        }else if (id == R.id.main_btn_rec){
            ctrlRec();//开始录像
        }else if (id == R.id.main_btn_preview) {
            changePreview();
        } else if (id == R.id.main_img_pic){
            mPicIV.setVisibility(View.GONE);
        }else if (id == R.id.main_btn_rec_list){
            RecListActivity.startActivity(this);
        }
    }

    private void changePreview() {

        int size =  mRecHelper.getCameraCount();
        if (mPreviewLayout.getChildCount() == 0){
            mBtnPreview.setText("关闭预览");
            for (int i = 0; i < size; i++) {
                SurfaceView surfaceView = new SurfaceView(mContext);
                LinearLayout.LayoutParams layoutParams =
                        new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.weight = 1;
                surfaceView.setLayoutParams(layoutParams);
                mPreviewLayout.addView(surfaceView);

                mRecHelper.setPreview(i,surfaceView.getHolder().getSurface());

            }
        }else{
            for (int i = 0; i < size; i++) {
                mRecHelper.setPreview(i,null);
            }
            mPreviewLayout.removeAllViews();
            mBtnPreview.setText("开始预览");
        }
    }
    public void ctrlRec() {
        if (mRecHelper.isRun()){
            mBtnRec.setText("开始录像");
            mRecHelper.stop();
        }else{
            mBtnRec.setText("停止录像");
            mRecHelper.start();
        }
    }

    @Override
    public void onBackPressed() {
        if (mRecHelper.isRun()){
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("是否停止录像？");
            builder.setNegativeButton("停止录像",
                    (dialog, which) -> {
                        ctrlRec();
                        dialog.dismiss();
                    });
            builder.setPositiveButton("后台录像",
                    (dialog, which) -> {
                        moveTaskToBack(true);
                        dialog.dismiss();
                    });
            builder.create().show();
        }else{
            super.onBackPressed();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        boolean isGrant = true;

        //判断是否每一个权限都同意了。
        for (int res : grantResults) {
            if (res != PackageManager.PERMISSION_GRANTED) {
                isGrant = false;
                break;
            }
        }

        //如果长度为0，则可能为未做任何选择，直接取消了。
        if (grantResults.length > 0 && isGrant) {
            RecService.start(mContext);
        } else {
            //进入APP信息页面
            Uri packageURI = Uri.parse("package:" + getPackageName());
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
            startActivity(intent);
            Toast.makeText(mContext, "不授权权限会导致语音识别无法正常使用！", Toast.LENGTH_SHORT).show();
        }
    }
}
